package logic

import (
	"fmt"
	"time"

	"github.com/spf13/cast"
)

const (
	MsgTypeNormal    = iota // 普通 用户消息
	MsgTypeWelcome          // 当前用户欢迎消息
	MsgTypeUserEnter        // 用户进入
	MsgTypeUserLeave        // 用户退出
	MsgTypeError            // 错误消息
)

type Message struct {
	User    *User     `json:"user"`
	Type    int       `json:"type"`
	Content string    `json:"content"`
	MsgTime time.Time `json:"msg_time"`

	ClientSendTime time.Time `json:"client_send_time"`

	Ats []string `json:"ats"`

	Users map[string]*User `json:"users"`
}

func NewMessage(u *User, msg, clientTime string) *Message {
	newMsg := &Message{
		User:    u,
		Type:    MsgTypeNormal,
		Content: msg,
		MsgTime: time.Now(),
	}

	if clientTime != "" {
		newMsg.ClientSendTime = time.Unix(0, cast.ToInt64(clientTime))
	}
	return newMsg
}

func NewErrorMessage(msg string) *Message {
	return &Message{
		User:    System,
		Type:    MsgTypeError,
		Content: msg,
		MsgTime: time.Now(),
	}
}

func NewWelcomeMessage(user *User) *Message {
	return &Message{
		User:    user,
		Type:    MsgTypeWelcome,
		Content: fmt.Sprintf("welcome %s enter room!", user.NickName),
		MsgTime: time.Now(),
	}
}

func NewUserEnterMessage(u *User) *Message {
	return &Message{
		User:    u,
		Type:    MsgTypeUserEnter,
		Content: u.NickName + "进入聊天室",
		MsgTime: time.Now(),
	}
}

func NewUserLeaveMessage(u *User) *Message {
	return &Message{
		User:    u,
		Type:    MsgTypeUserLeave,
		Content: u.NickName + "离开聊天室",
		MsgTime: time.Now(),
	}
}
